import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';

import { aroAnimation } from '../../../animation';
import { tick } from '@angular/core/testing';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css'],
  animations: [aroAnimation]
})
export class SearchComponent implements OnInit {

  public state: boolean = false;

  public keyword: string = '';

  public keywordArr: Array<any> = [];
  public tempKeywordArr: Array<any> = [];

  public keywordlist: Array<any> = JSON.parse(localStorage.getItem('Keyword'));

  constructor(private location: Location, private currentRouter: ActivatedRoute, private router: Router
  ) { }

  ngOnInit() {
    if (this.keywordlist) {
      this.state = true;
    }
  }


  public goBack(): void {
    this.location.back();
  }

  public goSearch_onclick() {

    //将历史记录存到本地
    let Keyword = JSON.parse(localStorage.getItem('Keyword'));
    if (Keyword) {
      this.keywordArr = Array.from(Keyword);
    }

    //对数组去重
    this.tempKeywordArr = this.keywordArr.filter(item => item != this.keyword);

    if (this.tempKeywordArr.length != this.keywordArr.length) {
      //unshift进数组
      this.tempKeywordArr.unshift(this.keyword);
    } else {
      //push进数组
      this.tempKeywordArr.push(this.keyword);
    }

    this.keywordArr = this.tempKeywordArr;

    // console.log(this.keywordArr);
    localStorage.setItem('Keyword', JSON.stringify(this.keywordArr));

    this.router.navigate(['./searchlist', this.keyword]);
  }

  //清除全部记录
  public clearKeywords_onclick() {
    localStorage.removeItem('Keyword');
    // this.keywordlist = [];
    this.state = false;
  }

  //清除单个记录
  public clearSingleKeyword_onclick(item) {
    // console.log(item);
    this.keywordlist = this.keywordlist.filter(keyword => keyword != item);
    localStorage.setItem('Keyword', JSON.stringify(this.keywordlist));
    if (this.keywordlist.length == 0) {
      localStorage.removeItem('Keyword');
      this.state = false;
    }
  }

  public goList_onclick(item): void {
    this.router.navigate(['./searchlist', item]);
  }


}
